<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>NoA | Free Deep Think</title>
    <style>
        :root {
            --primary-color: #0E1117;
            --secondary-color: #262730;
            --accent-color: #FF4B4B;
            --text-color: #FAFAFA;
            --font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
            --border-radius: 0.5rem;
        }
        body {
            background-color: var(--primary-color);
            color: var(--text-color);
            font-family: var(--font-family);
            margin: 0;
            padding: 2rem;
            font-size: 16px;
            line-height: 1.6;
        }
        h1, h2 {
            color: var(--text-color);
            border-bottom: 1px solid var(--secondary-color);
            padding-bottom: 0.5rem;
            margin-top: 2rem;
            margin-bottom: 1rem;
        }
        h1 {
            text-align: center;
            font-size: 2.5rem;
            border-bottom: none;
        }
        h2 {
            font-size: 1.75rem;
        }
        .container {
            width: 100%;
            max-width: 800px;
            margin: 0 auto;
            background-color: var(--primary-color);
            padding: 2rem;
            border-radius: var(--border-radius);
            margin-bottom: 2rem;
        }
        .section {
            background-color: var(--secondary-color);
            padding: 2rem;
            border-radius: var(--border-radius);
            margin-bottom: 2rem;
        }
        .hidden {
            display: none;
        }
        label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 500;
        }
        input, textarea, button, select {
            width: 100%;
            padding: 0.75rem;
            margin-bottom: 1rem;
            border: 1px solid var(--secondary-color);
            background-color: #1C1E25;
            color: var(--text-color);
            border-radius: var(--border-radius);
            box-sizing: border-box;
            font-family: inherit;
            font-size: 1rem;
        }
        input:focus, textarea:focus, select:focus {
            outline: none;
            border-color: var(--accent-color);
            box-shadow: 0 0 0 2px rgba(255, 75, 75, 0.3);
        }
        textarea {
            min-height: 120px;
            resize: vertical;
        }
        button {
            cursor: pointer;
            background-color: var(--accent-color);
            color: var(--text-color);
            font-weight: bold;
            border: none;
            transition: background-color: 0.3s ease;
        }
        button:hover {
            background-color: #E03C3C;
        }
        button:disabled {
            background-color: #555;
            cursor: not-allowed;
        }
        #log-container {
            height: 400px;
            background-color: #000;
            border: 1px solid var(--secondary-color);
            border-radius: var(--border-radius);
            padding: 1rem;
            overflow-y: scroll;
            font-family: 'Menlo', 'Consolas', 'Courier New', monospace;
            font-size: 0.9em;
            color: #C0C0C0;
            white-space: pre-wrap;
        }
        /* MODIFIED: Terminal-like style for ASCII graph display */
        #graph-container {
            min-height: 400px;
            background-color: #000;
            border: 1px solid var(--secondary-color);
            border-radius: var(--border-radius);
            padding: 1rem;
            overflow-x: auto;
            font-family: 'Menlo', 'Consolas', 'Courier New', monospace;
            font-size: 0.9em;
            color: #C0C0C0;
            white-space: pre;
        }
        #graph-container p {
            color: #888;
            white-space: pre-wrap; /* Allow placeholder text to wrap */
        }
        .mbti-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
            gap: 1rem;
            background-color: #1C1E25;
            padding: 1rem;
            border-radius: var(--border-radius);
            margin-bottom: 1rem;
        }
        .mbti-option {
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        .mbti-option input[type="checkbox"] {
            width: auto;
            margin-bottom: 0;
        }
        .mbti-option label {
            margin-bottom: 0;
            font-weight: normal;
        }
        #results-container pre {
            background-color: #000;
            padding: 1rem;
            border-radius: var(--border-radius);
            white-space: pre-wrap;
            word-wrap: break-word;
        }
    </style>
</head>
<body>
    <h1>It takes a village of agents to raise an agent</h1>

    <div class="container">
        <div id="graph-architecture" class="section">
            <h2>Graph Architecture</h2>
            <form id="graph-params-form">
                <label for="llm_provider">LLM Provider:</label>
                <select id="llm_provider" name="llm_provider">
                    <option value="Gemini">Google Gemini</option>
                    <option value="Ollama">Local Ollama</option>
                </select>
                <div class="mbti-option" style="margin-bottom: 1rem; margin-top: 0.5rem;">
                    <input type="checkbox" id="debug_mode" name="debug_mode" value="true">
                    <label for="debug_mode">🚀 Enable Debug Mode (Uses Instant Mock LLM)</label>
                </div>
                <div id="ollama-model-section" class="hidden">
                    <label for="ollama_model">Ollama Model Name:</label>
                    <input type="text" id="ollama_model" name="ollama_model" value="dengcao/Qwen3-30B-A3B-Instruct-2507:latest">
                </div>
                <label for="cot_trace_depth">CoT trace depth (max 32):</label>
                <input type="number" id="cot_trace_depth" name="cot_trace_depth" value="2" max="32" min="2" required>
                <label for="num_epochs">Number of epochs:</label>
                <input type="number" id="num_epochs" name="num_epochs" value="1" required>
                <label for="vector_word_size">Vector word size (Number of verbs per agent):</label>
                <input type="number" id="vector_word_size" name="vector_word_size" value="2" min="2" max="20" required>
                <label for="prompt_alignment">Prompt alignment (0.1-2.0):</label>
                <input type="number" id="prompt_alignment" name="prompt_alignment" step="0.1" min="0.1" max="2.0" value="1.0" required>
                <label for="density">Density (0.1-2.0):</label>
                <input type="number" id="density" name="density" step="0.1" min="0.1" max="2.0" value="1.0" required>
                <label for="learning_rate">Learning rate (0.1-2.0):</label>
                <input type="number" id="learning_rate" name="learning_rate" step="0.1" min="0.1" max="2.0" value="0.1" required>
                <label>MBTI Archetypes (select at least 2):</label>
                <div class="mbti-grid">
                    <div class="mbti-option"><input type="checkbox" id="mbti-istj" name="mbti_archetypes" value="ISTJ" checked><label for="mbti-istj">ISTJ (Inspector)</label></div>
                    <div class="mbti-option"><input type="checkbox" id="mbti-isfj" name="mbti_archetypes" value="ISFJ" checked><label for="mbti-isfj">ISFJ (Protector)</label></div>
                    <div class="mbti-option"><input type="checkbox" id="mbti-infj" name="mbti_archetypes" value="INFJ"><label for="mbti-infj">INFJ (Advocate)</label></div>
                    <div class="mbti-option"><input type="checkbox" id="mbti-intj" name="mbti_archetypes" value="INTJ"><label for="mbti-intj">INTJ (Architect)</label></div>
                    <div class="mbti-option"><input type="checkbox" id="mbti-istp" name="mbti_archetypes" value="ISTP"><label for="mbti-istp">ISTP (Virtuoso)</label></div>
                    <div class="mbti-option"><input type="checkbox" id="mbti-isfp" name="mbti_archetypes" value="ISFP"><label for="mbti-isfp">ISFP (Adventurer)</label></div>
                    <div class="mbti-option"><input type="checkbox" id="mbti-infp" name="mbti_archetypes" value="INFP"><label for="mbti-infp">INFP (Mediator)</label></div>
                    <div class="mbti-option"><input type="checkbox" id="mbti-intp" name="mbti_archetypes" value="INTP"><label for="mbti-intp">INTP (Logician)</label></div>
                    <div class="mbti-option"><input type="checkbox" id="mbti-estp" name="mbti_archetypes" value="ESTP"><label for="mbti-estp">ESTP (Entrepreneur)</label></div>
                    <div class="mbti-option"><input type="checkbox" id="mbti-esfp" name="mbti_archetypes" value="ESFP"><label for="mbti-esfp">ESFP (Entertainer)</label></div>
                    <div class="mbti-option"><input type="checkbox" id="mbti-enfp" name="mbti_archetypes" value="ENFP"><label for="mbti-enfp">ENFP (Campaigner)</label></div>
                    <div class="mbti-option"><input type="checkbox" id="mbti-entp" name="mbti_archetypes" value="ENTP"><label for="mbti-entp">ENTP (Debater)</label></div>
                    <div class="mbti-option"><input type="checkbox" id="mbti-estj" name="mbti_archetypes" value="ESTJ"><label for="mbti-estj">ESTJ (Executive)</label></div>
                    <div class="mbti-option"><input type="checkbox" id="mbti-esfj" name="mbti_archetypes" value="ESFJ"><label for="mbti-esfj">ESFJ (Consul)</label></div>
                    <div class="mbti-option"><input type="checkbox" id="mbti-enfj" name="mbti_archetypes" value="ENFJ"><label for="mbti-enfj">ENFJ (Protagonist)</label></div>
                    <div class="mbti-option"><input type="checkbox" id="mbti-entj" name="mbti_archetypes" value="ENTJ"><label for="mbti-entj">ENTJ (Commander)</label></div>
                </div>
                <label for="prompt">Prompt:</label>
                <textarea id="prompt" name="prompt" required>Is there a singular, all-encompassing, coherent theoretical framework of physics that fully explains and links together all physical aspects of the universe? Design one.</textarea>
                <button type="submit" id="run-button">Build and Run Graph</button>
            </form>
        </div>
    </div>
    <div class="container">
        <h2>Real-time Graph Activity</h2>
        <div id="log-container"></div>
    </div>
    <div class="container">
        <h2>Graph Visualization</h2>
        <!-- MODIFIED: Updated placeholder text -->
        <div id="graph-container">
            <p>ASCII graph will be displayed here after the process starts...</p>
        </div>
    </div>
    <div class="container hidden" id="results-container">
        <h2>Final Result</h2>
        <div id="final-solution"></div>
    </div>

<script>
    const graphParamsForm = document.getElementById('graph-params-form');
    const runButton = document.getElementById('run-button');
    const logContainer = document.getElementById('log-container');
    const graphContainer = document.getElementById('graph-container');
    const resultsContainer = document.getElementById('results-container');
    const finalSolutionContainer = document.getElementById('final-solution');
    const llmProviderSelect = document.getElementById('llm_provider');
    const ollamaModelSection = document.getElementById('ollama-model-section');
    const debugModeCheckbox = document.getElementById('debug_mode');

    llmProviderSelect.addEventListener('change', (e) => {
        ollamaModelSection.classList.toggle('hidden', e.target.value !== 'Ollama');
    });

    debugModeCheckbox.addEventListener('change', (e) => {
        const isDebug = e.target.checked;
        llmProviderSelect.disabled = isDebug;
        ollamaModelSection.classList.toggle('hidden', isDebug || llmProviderSelect.value !== 'Ollama');
    });

    const addLogMessage = (text, options = {}) => {
        const p = document.createElement('p');
        if (options.isHTML) p.innerHTML = text;
        else p.textContent = text;
        if (options.color) p.style.color = options.color;
        logContainer.appendChild(p);
        logContainer.scrollTop = logContainer.scrollHeight;
    };

    graphParamsForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        const formData = new FormData(graphParamsForm);
        const params = {};
        formData.forEach((value, key) => {
            if (key === 'mbti_archetypes') {
                if (!params[key]) params[key] = [];
                params[key].push(value);
            } else {
                params[key] = value;
            }
        });
        
        if (!formData.has('debug_mode')) {
            params.debug_mode = 'false';
        }

        if (!params.mbti_archetypes || params.mbti_archetypes.length < 2) {
            alert('Please select at least 2 MBTI archetypes.');
            return;
        }
        runButton.disabled = true;
        runButton.textContent = 'Processing...';
        logContainer.innerHTML = ''; 
        graphContainer.innerHTML = '<p>ASCII graph will be displayed here after the process starts...</p>';
        resultsContainer.classList.add('hidden');
        finalSolutionContainer.innerHTML = '';
        addLogMessage('Sending request to build and run graph...');
        try {
            const response = await fetch('/build_and_run_graph', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ params })
            });
            const result = await response.json();
            if (!response.ok) {
                addLogMessage(`Error: ${result.message}`, { color: 'red' });
                if(result.traceback) {
                    const pre = document.createElement('pre');
                    pre.style.color = '#ff8c8c';
                    pre.textContent = result.traceback;
                    logContainer.appendChild(pre);
                }
                return;
            }
            addLogMessage(`<strong>✅ ${result.message}</strong>`, { isHTML: true, color: 'lime' });
            if (result.final_solution && !result.final_solution.error) {
                const solution = result.final_solution;
                finalSolutionContainer.innerHTML = `
                    <h3>Proposed Solution</h3><pre><code>${solution.proposed_solution || 'N/A'}</code></pre>
                    <h3>Reasoning</h3><pre><code>${solution.reasoning || 'N/A'}</code></pre>
                    <h3>Skills Used</h3><p>${(solution.skills_used || []).join(', ') || 'N/A'}</p>`;
                resultsContainer.classList.remove('hidden');
            } else {
                 addLogMessage(`⚠️ Server finished but returned no valid solution.`, { color: 'orange' });
                 if(result.final_solution?.error) {
                    addLogMessage(`Error details: ${result.final_solution.error}`, { color: 'orange' });
                 }
            }
        } catch (error) {
            addLogMessage(`A client-side error occurred: ${error.message}`, { color: 'red' });
        } finally {
            runButton.disabled = false;
            runButton.textContent = 'Build and Run Graph';
        }
    });

    function tryParseJson(message) {
        try {
            return JSON.parse(message);
        } catch (e) { return null; }
    }

    const eventSource = new EventSource('/stream_log');

    eventSource.onmessage = async function(event) {
        const rawMessage = event.data;

        // --- MODIFIED: Listen for 'graph_ascii' and render in terminal ---
        if (rawMessage.includes('__start__')) {

            addLogMessage('>>> ASCII Graph received. Rendering...', { color: 'cyan' });
            graphContainer.textContent = rawMessage;
            addLogMessage('>>> Graph rendered.', { color: 'lime' });
        } else {
            addLogMessage(rawMessage);
        }
    }; 

    eventSource.onerror = function(err) {
        console.error("EventSource failed:", err);
        addLogMessage("Error: Connection to server log stream lost. Please refresh and try again.", { color: 'red' });
        eventSource.close();
    };
</script>
</body>
</html>